//收银台
<template>
  <div class="cashier-desk">
    <el-container >
      <el-header class="menu" height="8vh">
        <nav-menu></nav-menu>
      </el-header>
      <el-main class="main-desk">
        <el-container >
          <el-header class="cashier-header" height="10vh">
            <cashier-info
              :date=date
              :name="staff.name"
              :shopping_no=shopping_no>
            </cashier-info>
          </el-header>
          <el-main class="cashier-main">
            <sale-table
              :sale-data="saleData"
              :handle-delete="handleDelete"
              :count-price="countPrice"
            ></sale-table>
          </el-main>
          <el-footer class="cashier-footer" height="10vh">
            <div class="row">
              <el-autocomplete
              placeholder="输入条码或商品名"
              class="good-input"
              :fetch-suggestions="querySearchAsync"
              v-model="info"
              @select="handleSelect"
              :debounce="10"
              :trigger-on-focus="true"
              >
              </el-autocomplete>
            </div>
            <div class="row">
              <el-select
                v-model="customer"
                filterable
                remote
                placeholder="输入会员名或电话号码"
                :loading="loading">
              </el-select>
            </div>
            <div class="row">
              <span>合计数量: {{totalNum}}</span>
            </div>
            <div class="row">
              <span>合计金额: {{totalCost}}</span>
            </div>
            <div class="row">
              <span>优惠金额: {{fullMinus.cash || 0}}</span>
            </div>
            <div class="row">
              <el-button
                class="cashier-desk-btn"
                type="primary"
                @click="onSubmit">结算
              </el-button>
            </div>
          </el-footer>
        </el-container>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import NavMenu from "../common/NavMenu";
  import SaleTable from "./SaleTable";
  import CashierInfo from "./CashierInfo";
  import {queryInventory} from "../../services/inventoryService";
  import moment  from "moment";
  export default {
    name: "CashierDesk",
    components: {CashierInfo, SaleTable, NavMenu},
    data(){
      return {
        loading:false,
        customer:{},
        /*
        customer{
          phone
          name
          lv
          point//可用积分
          newPoint//积分变化数据
          exp//经验增长数据
        }
        **/
        saleData:[],
        info:'',
        staff:{},
        goodList:[],
        timeout:null,
        totalCost:0,
        totalNum:0,
        shopping_no:'XS'+this._func.getId(),
        date:moment(new Date()).format('yyyy-MM-DD'),
        fullMinus:{},
        //免费赠送的商品
        freeGoods:[],
      }
    },
    methods:{
      //远程模糊查询
      loadGoods(){
        this.goodList=[];
        queryInventory(this.info).then(success=>{
          if(/^\d+$/.test(this.info)){
            success.data.forEach((item)=>{
              let temp={
                value:'',
                goodModel: {},
                inventoryGood: {},
                tagList:[]
              }
              temp.value=item.good.good.barcode;
              temp.goodModel=item.good;
              temp.inventoryGood=item.inventoryGoods;
              temp.tagList=item.tagList;
              this.goodList.push(temp);
            })
          }else{
            success.data.forEach((item)=>{
              let temp={
                value:'',
                goodModel: {},
                inventoryGood: {},
                tagList:[]
              }
              temp.value=item.good.good.name;
              temp.goodModel=item.good;
              temp.inventoryGood=item.inventoryGoods;
              temp.tagList=item.tagList;
              this.goodList.push(temp);
            })
          }
        },failed=>{
          this.$message({
            type:'error',
            message:'商品搜索失败',
          })
        })
      },
      //远程查询
      querySearchAsync(queryString, cb) {
        this.loadGoods()
        var results=this.goodList;
        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 0);
      },

      //下拉框选择商品
      handleSelect(item) {
        //console.log(item);
        //console.log(JSON.stringify(item))
        let good={};
        for(let i=0;i<this.saleData.length;i++){
          if(this.saleData[i].goodModel.good.barcode==item.goodModel.good.barcode
            && this.saleData[i].tags[0]!=this._mytype.produceType.FREE.str){
            this.saleData[i].num+=1;
            this.countPrice(i);
            good=this.saleData[i];
            //清空输入框内容
            this.info='';
            this.countTotalPrice();
            return;
          }
        }
        //this.shopping_no='XS'+this._date.getDate(0);
        let temp=this._myobj.SaleGood.createNew()
        temp.num=1;
        temp.goodModel=item.goodModel;
        temp.actualPrice=item.goodModel.good.price;
        temp.totalPrice=temp.actualPrice;
        good=temp;
        //将选择的商品添加进购物列表
        this.saleData.push(temp);
        console.log(JSON.stringify(this.saleData))
        //清空输入框内容
        this.info='';
        this.countTotalPrice()
      },
      /*
      *@Author Anqing Liang
      *@Description
      *@Date 19:20 2021/3/2
      *@Param SaleGood item
      *@Return
      **/
      async fullMinusCount(list){
        /*********FullMinus***********/
        console.log('*********fullMinus********')
        let total=0;
        let totalNum=0;
        this.fullMinus={};
        if(this._func.isEmpty(this.fullMinus)){
          let resp=await this._get.findFullMinusByTimeOrId('');
          this.fullMinus=this._myobj.FullMinus.createNew(resp);
        }
        /*********达标金额计算与标签更新*********/
        Array.from(list).forEach(item=>{
          total+=item.totalPrice;
          item.tags=[];
          item.tags.push(this._mytype.produceType.FULLMINUS.str);
          this.fullMinus.goodsBarcode.push(item.goodModel.good.barcode);
        })
        /*********达标金额计算与标签更新*********/
        if(total<this.fullMinus.nowCondition){
          this.fullMinus.cash=0;
          this.fullMinus.freeGoods=[];
          console.log(JSON.stringify(this.fullMinus));
          console.log('*********fullMinus********')
          return;
        }
        /*********活动晋级与更新******/
        if(this.fullMinus.nextCondition>-1 && total>=this.fullMinus.nextCondition){
          let resp= await this._get.findFullMinusByIdAndTotal(this.fullMinus.id,total)
          this.fullMinus.update(resp);
          this.fullMinus.total=total;
        }
        /*********活动晋级与更新******/

        /******额外赠送商品********/
        if(this.fullMinus.freeGoods.length>0){
          let list=Array.from(this.fullMinus.freeGoods);
          if(list[0].barcode==this._mytype.DEFAULT){
            this.freeGoods=[];
            this.saleData.forEach((item,index)=>{
              if(item.tags==this._mytype.produceType.FREE.str){
                this.saleData.splice(index,1);
              }
            })
            console.log(JSON.stringify(this.fullMinus));
            console.log('*********fullMinus********')
            return;
          }
          let len=list.length;
          for(let i=0;i<len;i++){
            let good=list[i];
            let index=this.saleData.findIndex(item=>item.goodModel.good.barcode==good.barcode);
            console.log(JSON.stringify(index));
            console.log(JSON.stringify(good));
            if(index>-1 &&this.saleData[index].tags[0]==this._mytype.produceType.FREE.str)
            {
              this.saleData[index].num=good.num;
              continue;
            }
            if(index>-1){
              //在待售商品表中减去免费赠送的商品
              this.saleData[index].num-=good.num;
              if(this.saleData[index].num<=0){
                this.saleData.splice(index,1);
              }
              //this.countTotalPrice();
            }
            this._post.findInventoryGoodByQuery(good.barcode).then(resp=>{
              let freeGood=this._myobj.SaleGood.createNew();
              freeGood.num=good.num;
              freeGood.goodModel=resp.good;
              console.log(JSON.stringify(resp.good))
              freeGood.actualPrice=0;
              freeGood.totalPrice=0;
              freeGood.tags.push(this._mytype.produceType.FREE.str);
              this.freeGoods.push(freeGood);
              this.saleData.push(freeGood);
              console.log(JSON.stringify(this.freeGoods));
              console.log(JSON.stringify(this.saleData));
            })
            //this.countTotalPrice();
          }
        }
        /******额外赠送商品********/

        console.log(JSON.stringify(this.fullMinus));
        console.log('*********fullMinus********')
        /*********FullMinus***********/
      },
      //从购物列表中删除商品
      handleDelete(index, row) {
        console.log(index, row);
        console.log(JSON.stringify(index));
        console.log(JSON.stringify(row));
        this.saleData.splice(index,1);
        this.countTotalPrice();
      },
      //计算单个商品总价 实际单价*数量=总价
      countPrice(index){
        //输入检测
        //如果价格中的字符不是数值则执行
        if(!/^(\d+|\d+.\d+)$/.test(this.saleData[index].actualPrice)){
          console.log('价格错误')
          this.saleData[index].actualPrice=this.saleData[index].actualPrice.replace(/[^\d.]/g,'');
        }
        //计算
        this.saleData[index].totalPrice=this.saleData[index].actualPrice*this.saleData[index].num;
        this.countTotalPrice();
        },
      //计算结算
      countTotalPrice(){
        this.totalCost=0;
        this.totalNum=0;
        let fullMinusGoods=[];

        //第一次遍历，处理参与活动的商品主体
        this.saleData.forEach(item=>{
          this.totalCost+=parseFloat(item.totalPrice);
          this.totalNum+=item.num;

          /********活动商品添加********/
          if(this._money.getDiscountType(item.goodModel.tagsList)==this._mytype.produceType.FULLMINUS) {
            console.log("该商品参与满减活动");
            fullMinusGoods.push(item);
          }
          /********活动商品添加********/
        })
        /********活动处理********/
        this.fullMinusCount(fullMinusGoods);
        /********活动处理********/
      },
      //获取销售商品表
      getSaleList(){
        let resp=[];
        this.saleData.forEach((item,index)=>{
          let temp={
            shopping_no:this.shopping_no,
            barcode:'',
            name:'',
            price:0,
            actualprice:'',
            num:0,
            totalprice:0,
            date:'',
            discount_id:''
          };
          temp.shopping_no=this.shopping_no+index
          temp.actualprice=item.actualPrice;
          temp.totalprice=item.totalPrice;
          temp.price=item.goodModel.good.price;
          temp.num=item.num;
          temp.barcode=item.goodModel.good.barcode;
          temp.name=item.goodModel.good.name;
          temp.discount_id=item.discount_id;
          temp.date=this.date;
          resp.push(temp);
        })
        return resp;
      },
      //提交结算
      onSubmit(){
        let saleList=this.getSaleList();
        this.$axios.post('/shopping/add',saleList)
          .then(
            this.$axios.post('/shopping/shoppingInfo/add',{
              shoppingno: this.shopping_no,
              date:this.date,
              num:this.totalNum,
              totalcost:this.totalCost,
              customer:'default',
              staff:this.$store.state.staff.account,
            })
          )
          .then(
            this.$message({
              message:this.shopping_no+'结算成功',
              type:'success'
            })
          )
          .then(
            ()=>{
              this.totalNum=0;
              this.totalCost=0;
              this.date=this._date.getDate(1);
              this.saleData=[];
              this.shopping_no='XS'+this._func.getId(),
              this.info='';
              this.goodList=[];
            }
          )
      }
    },
    created() {
      this.staff=this.$store.state.staff;
      console.log(this.staff)
    }
  }
</script>

<style>
  .cashier-desk .menu{
    padding: 0;
  }
  .cashier-desk .good-input{
    width: 20vw;
    padding: 0;
    margin: 0;
    /*background-color: red;*/
  }
  .cashier-desk .main-desk{
    height: 100%;
  }
  .cashier-desk .cashier-header{
    background-color: #99CCFF;
  }
  .cashier-desk .cashier-main{
    height: 75vh;
  }
  .cashier-desk .cashier-footer{
    background-color: #99CCFF;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: center;
    padding: 0;
    margin: 0;
  }
  .cashier-desk .el-main{
    padding: 0;
  }
  .row{
    height: 100%;
    margin: 0;
    display: flex;
    font-size: 1.4rem;
  }
.cashier-desk-btn{
  display: flex;
  justify-content: start;
}
</style>

